#! /usr/bin/env python
# -*- coding: utf8 -*-

import sys
import random
import zope.interface

import base
import sys

if __name__ == '__main__':
    print "You shouldn't be running this file!"
    sys.exit()

class swap(object):
    zope.interface.implements(base.IAlgorithm)
    name = "swap"

    def __init__(self, node):
        self.__others = False

        if node.find("./parameters/withOthers") != None and node.find("./parameters/withOthers").text.lower() == "true":
            self.__others = True

    def __call__(self, node, parentMap, root):
        if node not in parentMap:
            return

        if self.__others:
            targets = root.findall(".//*")
            targets = filter(lambda x:x not in node, targets)


        if targets == []:
            return

        for i in xrange(len(targets)):
            oNode = random.choice(targets)
            if oNode in parentMap and oNode in parentMap[oNode]:
                break
            else:
                targets.remove(oNode)

        lista = [node, oNode]

        try:
            parentMap[node].remove(node)
            parentMap[oNode].remove(oNode)

            parentMap[node].append(oNode)
            parentMap[oNode].append(node)
            parentMap[oNode], parentMap[node] = parentMap[node], parentMap[oNode]
        except Exception:
            pass

__plugins__ = (swap, )
